import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import './service_notification_page.dart';
import './promotion_page.dart';
import './chat_page.dart';

class MessagePage extends StatefulWidget {
  const MessagePage({super.key});

  @override
  State<MessagePage> createState() => _MessagePageState();
}

class _MessagePageState extends State<MessagePage> {
  final RefreshController _systemRefreshController = RefreshController();
  final RefreshController _chatRefreshController = RefreshController();

  Future<void> _onRefresh(bool isSystemMessage) async {
    // 模拟网络请求
    await Future.delayed(const Duration(seconds: 1));
    
    if (isSystemMessage) {
      _systemRefreshController.refreshCompleted();
    } else {
      _chatRefreshController.refreshCompleted();
    }
  }

  Future<void> _onLoading(bool isSystemMessage) async {
    // 模拟网络请求
    await Future.delayed(const Duration(seconds: 1));
    
    if (isSystemMessage) {
      _systemRefreshController.loadComplete();
    } else {
      _chatRefreshController.loadComplete();
    }
  }

  @override
  void dispose() {
    _systemRefreshController.dispose();
    _chatRefreshController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        backgroundColor: const Color(0xFFF7F7F7),
        appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0,
          title: TabBar(
            isScrollable: false,
            labelColor: Theme.of(context).colorScheme.primary,
            unselectedLabelColor: Colors.grey,
            indicator: const BoxDecoration(),
            labelStyle: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
            ),
            unselectedLabelStyle: const TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w500,
            ),
            labelPadding: EdgeInsets.zero,
            padding: const EdgeInsets.only(right: 100),
            dividerColor: Colors.transparent,
            tabs: const [
              Tab(text: '系统消息'),
              Tab(text: '聊天消息'),
            ],
          ),
          bottom: const PreferredSize(
            preferredSize: Size.fromHeight(0.5),
            child: Divider(
              height: 0.5,
              color: Color(0xFFEEEEEE),
            ),
          ),
        ),
        body: TabBarView(
          children: [
            // 系统消息列表
            Builder(
              builder: (context) {
                final bool hasMoreContent = MediaQuery.of(context).size.height < 600; // 根据实际内容调整
                return SmartRefresher(
                  controller: _systemRefreshController,
                  enablePullDown: true,
                  enablePullUp: hasMoreContent,
                  header: const ClassicHeader(
                    idleText: "下拉刷新",
                    releaseText: "松开刷新",
                    refreshingText: "正在刷新...",
                    completeText: "刷新完成",
                    failedText: "刷新失败",
                    height: 38,
                    refreshingIcon: SizedBox(
                      width: 15,
                      height: 15,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                      ),
                    ),
                    textStyle: TextStyle(
                      fontSize: 13,
                      color: Color(0xFF666666),
                    ),
                  ),
                  footer: const ClassicFooter(
                    idleText: "上拉加载更多",
                    loadingText: "正在加载...",
                    noDataText: "没有更多数据了",
                    failedText: "加载失败，点击重试",
                    canLoadingText: "松手加载更多",
                    height: 38,
                    loadingIcon: SizedBox(
                      width: 15,
                      height: 15,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                      ),
                    ),
                    textStyle: TextStyle(
                      fontSize: 13,
                      color: Color(0xFF666666),
                    ),
                  ),
                  onRefresh: () => _onRefresh(true),
                  onLoading: () => _onLoading(true),
                  child: ListView(
                    padding: EdgeInsets.zero,
                    children: [
                      _buildMessageItem(
                        context,
                        icon: Icons.notifications_outlined,
                        title: '服务通知',
                        subtitle: '您的搬家订单已完成',
                        time: '10:30',
                        unreadCount: 2,
                        iconColor: Colors.blue,
                        onTap: () => Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const ServiceNotificationPage(),
                          ),
                        ),
                      ),
                      _buildMessageItem(
                        context,
                        icon: Icons.local_offer_outlined,
                        title: '优惠活动',
                        subtitle: '限时特惠：大件搬运8折优惠',
                        time: '昨天',
                        unreadCount: 1,
                        iconColor: Colors.orange,
                        onTap: () => Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const PromotionPage(),
                          ),
                        ),
                      ),
                      _buildMessageItem(
                        context,
                        icon: Icons.security_outlined,
                        title: '系统通知',
                        subtitle: '您的账号已完成实名认证',
                        time: '星期日',
                        unreadCount: 0,
                        iconColor: Colors.green,
                      ),
                      _buildMessageItem(
                        context,
                        icon: Icons.receipt_outlined,
                        title: '订单提醒',
                        subtitle: '您有一笔订单待支付',
                        time: '上周',
                        unreadCount: 1,
                        iconColor: Colors.red,
                      ),
                      _buildMessageItem(
                        context,
                        icon: Icons.star_outline,
                        title: '评价提醒',
                        subtitle: '您有订单待评价',
                        time: '上周',
                        unreadCount: 0,
                        iconColor: Colors.amber,
                      ),
                    ],
                  ),
                );
              },
            ),
            // 聊天消息列表
            Builder(
              builder: (context) {
                final bool hasMoreContent = MediaQuery.of(context).size.height < 400; // 根据实际内容调整
                return SmartRefresher(
                  controller: _chatRefreshController,
                  enablePullDown: true,
                  enablePullUp: hasMoreContent,
                  header: const ClassicHeader(
                    idleText: "下拉刷新",
                    releaseText: "松开刷新",
                    refreshingText: "正在刷新...",
                    completeText: "刷新完成",
                    failedText: "刷新失败",
                    height: 38,
                    refreshingIcon: SizedBox(
                      width: 15,
                      height: 15,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                      ),
                    ),
                    textStyle: TextStyle(
                      fontSize: 13,
                      color: Color(0xFF666666),
                    ),
                  ),
                  footer: const ClassicFooter(
                    idleText: "上拉加载更多",
                    loadingText: "正在加载...",
                    noDataText: "没有更多数据了",
                    failedText: "加载失败，点击重试",
                    canLoadingText: "松手加载更多",
                    height: 38,
                    loadingIcon: SizedBox(
                      width: 15,
                      height: 15,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                      ),
                    ),
                    textStyle: TextStyle(
                      fontSize: 13,
                      color: Color(0xFF666666),
                    ),
                  ),
                  onRefresh: () => _onRefresh(false),
                  onLoading: () => _onLoading(false),
                  child: ListView(
                    padding: EdgeInsets.zero,
                    children: [
                      _buildMessageItem(
                        context,
                        icon: Icons.support_agent,
                        title: '在线客服',
                        subtitle: '请问还有什么可以帮您？',
                        time: '星期一',
                        unreadCount: 0,
                        iconColor: Theme.of(context).colorScheme.primary,
                        onTap: () => Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const ChatPage(title: '在线客服'),
                          ),
                        ),
                      ),
                      _buildMessageItem(
                        context,
                        icon: Icons.person_outline,
                        title: '张师傅',
                        subtitle: '好的，我已经在路上了',
                        time: '昨天',
                        unreadCount: 1,
                        iconColor: Colors.blue,
                        onTap: () => Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const ChatPage(title: '张师傅'),
                          ),
                        ),
                      ),
                      _buildMessageItem(
                        context,
                        icon: Icons.person_outline,
                        title: '李师傅',
                        subtitle: '请问您的具体地址是？',
                        time: '上周',
                        unreadCount: 0,
                        iconColor: Colors.blue,
                        onTap: () => Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const ChatPage(title: '李师傅'),
                          ),
                        ),
                      ),
                    ],
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMessageItem(
    BuildContext context, {
    required IconData icon,
    required String title,
    required String subtitle,
    required String time,
    required int unreadCount,
    required Color iconColor,
    VoidCallback? onTap,
  }) {
    return InkWell(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.all(15),
        decoration: const BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(
              color: Color(0xFFEEEEEE),
              width: 0.5,
            ),
          ),
        ),
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: iconColor.withOpacity(0.1),
                shape: BoxShape.circle,
              ),
              child: Icon(
                icon,
                color: iconColor,
                size: 24,
              ),
            ),
            const SizedBox(width: 15),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        title,
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      Text(
                        time,
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey[500],
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 4),
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          subtitle,
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.grey[600],
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      if (unreadCount > 0) ...[
                        const SizedBox(width: 8),
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 6,
                            vertical: 2,
                          ),
                          decoration: BoxDecoration(
                            color: Colors.red,
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Text(
                            unreadCount.toString(),
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 12,
                            ),
                          ),
                        ),
                      ],
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
} 